//
//  SSDKPluginDeviceUtil.m
//  SuperSDKPluginTools
//
//  Created by wyht－ios－dev on 2017/7/28.
//  Copyright © 2017年 WYHT. All rights reserved.
//

#import "SSDKPluginDeviceUtil.h"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import <AVFoundation/AVFoundation.h>
#import <AdSupport/AdSupport.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "sys/utsname.h"
#include <ifaddrs.h>
#include <arpa/inet.h>
#import <UIKit/UIKit.h>
#import "SSDKPluginReachability.h"
#import <AppTrackingTransparency/ATTrackingManager.h>
#import "SSDKKeychain.h"

@implementation SSDKPluginDeviceUtil

static NSString *LOCALRECORD_DEVICEID=@"";

+(NSString *) getVersionCode {
    NSString *appInnerVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    return appInnerVersion==nil?@"unknown":appInnerVersion;
}

+(NSString *) getVersionName {
    NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    return appVersion==nil?@"unknown":appVersion;
}

+(NSString *) getDeviceID {
    return [SSDKPluginDeviceUtil getDeviceUniqId];
}

+(NSString *) getOS {
    return @"IOS";
}

+(NSString *) getOSVersion {
    NSString *osVersion = [[UIDevice currentDevice] systemVersion];
    return osVersion==nil?@"unknown":osVersion;
}

+(NSString *) getDeviceType {
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceVersion = [NSString stringWithFormat:@"%s", systemInfo.machine];
    return deviceVersion==nil?@"unknown":deviceVersion;
}

+(NSString *) getDeviceModel {
    return @"apple";
}

+(NSString *) getIDFA {
    return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
}

+(NSString *) getDeviceUniqId{
    NSString * identifier = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    NSString *uniqId = [SSDKKeychain passwordForService:identifier account:[identifier stringByAppendingString:@".deveice.uniqid"]];
    NSError *error = nil;
    if (uniqId == nil || [uniqId isEqualToString:@""] || uniqId.length == 0) {
        uniqId = [SSDKPluginDeviceUtil getIDFA];
        if (uniqId == nil || [uniqId isEqualToString:@""] || uniqId.length == 0 || [uniqId isEqualToString:@"00000000-0000-0000-0000-000000000000"]) {
            uniqId = [[NSUUID UUID] UUIDString];
        }
        BOOL succcess= [SSDKKeychain setPassword:uniqId
                                    forService:identifier
                                       account:[identifier stringByAppendingString:@".deveice.uniqid"]
                                         error:&error];
        uniqId = succcess ? uniqId : @"00000000-0000-0000-0000-000000000000";
    }
    return uniqId;
}

+ (void) requestIDFA:(void(^)(NSString *idfa))result {
    if (@available(iOS 14, *)) {
        if (ATTrackingManager.trackingAuthorizationStatus == ATTrackingManagerAuthorizationStatusNotDetermined) {
            [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
                if (result) result([self getIDFA]);
            }];
        }else{
            if (result) result([self getIDFA]);
        }
    } else {
        if (result) result([self getIDFA]);
    }
}

+(NSString *) getIDFV {
    NSString *idfv = [[UIDevice currentDevice].identifierForVendor UUIDString];
    return idfv;
}

+(NSString *) getOP {
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [info subscriberCellularProvider];
    NSString *mobile;
    if (!carrier.isoCountryCode) {
        mobile = @"NO SIM";
    } else {
        mobile = [carrier carrierName];
    }
    return mobile;
}

+(NSString *) getNetwork {
    NSString *netconnType = @"";
    SSDKPluginReachability *reach = [SSDKPluginReachability reachabilityWithHostName:@"www.baidu.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:// 没有网络
            netconnType = @"No Network";
            break;
        case ReachableViaWiFi:// Wifi
            netconnType = @"Wifi";
            break;
        case ReachableViaWWAN:// 手机自带网络
        {
            // 获取手机网络类型
            CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
            NSString *currentStatus = info.currentRadioAccessTechnology;
            if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyGPRS"]) {
                netconnType = @"2G";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyEdge"]) {
                netconnType = @"2G";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyWCDMA"]){
                netconnType = @"3G";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSDPA"]){
                netconnType = @"3.5G HSDPA";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSUPA"]){
                netconnType = @"3.5G HSUPA";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMA1x"]){
                netconnType = @"2G";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORev0"]){
                netconnType = @"3G";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevA"]){
                netconnType = @"3G";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevB"]){
                netconnType = @"3G";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyeHRPD"]){
                netconnType = @"3.5G eHRPD";
            }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyLTE"]){
                netconnType = @"4G";
            }
        }
            break;
        default:
            break;
    }
    return netconnType;
}


+(NSString *) getResolution {
    CGRect rect_screen = [[UIScreen mainScreen] bounds];
    CGSize size_screen = rect_screen.size;
    CGFloat scale_screen = [UIScreen mainScreen].scale;
    CGFloat width = size_screen.width*scale_screen;
    CGFloat height = size_screen.height*scale_screen;
    NSString *widthStr=[NSString stringWithFormat:@"%g",width];
    NSString *heightStr=[NSString stringWithFormat:@"%g",height];
    return [[widthStr stringByAppendingString:@"*"] stringByAppendingString:heightStr];
}



// 判断应用是否有用户授予的权限
+ (BOOL) hasAuthorityMedia:(NSString *)mediaType {
    //读取设备授权状态
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    return authStatus != AVAuthorizationStatusRestricted && authStatus != AVAuthorizationStatusDenied;
}

#pragma mark - 摄像头相关
// 判断设备是否有摄像头
+ (BOOL) isCameraAvailable {
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

// 前置的摄像头是否可用
+ (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

// 后置的摄像头是否可用
+ (BOOL) isRearCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

// 检查摄像头是否支持录像
+ (BOOL) doesCameraSupportShootingVideos {
    return [SSDKPluginDeviceUtil cameraSupportsMedia:( NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypeCamera];
}

// 检查摄像头是否支持拍照
+ (BOOL) doesCameraSupportTakingPhotos {
    return [SSDKPluginDeviceUtil cameraSupportsMedia:( NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

#pragma mark - 相册文件选取相关
// 相册是否可用
+ (BOOL) isPhotoLibraryAvailable {
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
}

// 是否可以在相册中选择视频
+ (BOOL) canUserPickVideosFromAlbum {
    return [SSDKPluginDeviceUtil cameraSupportsMedia:( NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

// 是否可以在相册中选择照片
+ (BOOL) canUserPickPhotosFromAlbum {
    return [SSDKPluginDeviceUtil cameraSupportsMedia:( NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

// 判断是否支持某种多媒体类型：拍照，视频
+ (BOOL) cameraSupportsMedia:(NSString *)mediaType sourceType:(UIImagePickerControllerSourceType)sourceType {
    __block BOOL result = NO;
    if ([mediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes =[UIImagePickerController availableMediaTypesForSourceType:sourceType];
    [availableMediaTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL*stop) {
        NSString *type = (NSString *)obj;
        if ([type isEqualToString:mediaType]){
            result = YES;
            *stop= YES;
        }
        
    }];
    return result;
}

@end
